import ws from 'k6/ws';
import { check } from 'k6';

export default function () {
    let url = 'ws://192.168.71.100:9999/ws';
    let params = { tags: { my_tag: 'hello' } };

    let response = ws.connect(url, params, function (socket) {
        socket.on('open', function open() {
            console.log('WebSocket connection established');
            socket.send(JSON.stringify({ message: 'Hello, server!' }));
        });

        socket.on('message', function (message) {
            console.log(`Received message: ${message}`);
            check(message, {
                'is hello': (msg) => msg === 'Hello, client!',
            });
        });

        socket.on('close', function () {
            console.log('WebSocket connection closed');
        });

        socket.on('error', function (e) {
            if (e.error() != 'websocket: close sent') {
                console.log('An unexpected error occurred: ', e.error());
            }
        });

        socket.setTimeout(function () {
            console.log('2 seconds passed, closing the socket');
            socket.close();
        }, 2000);
    });

    check(response, { 'status is 101': (r) => r && r.status === 101 });
}